package com.qfjg.webcore.common;

import java.io.*;
import java.util.ArrayList;
import java.util.UUID;


public class Utils {

    public static  String getException(Exception ex){
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        ex.printStackTrace(pw);
        return  sw.getBuffer().toString();
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }



    public static String getExtentsion(String fileName){
        if(fileName.contains(".")){
            if(fileName.lastIndexOf(".")==fileName.length()) return "";
            return fileName.substring(fileName.lastIndexOf(".")+1);
        }
        else return "";
    }

    public static String getFileNameNoExtension(String fileName){
        if(fileName.contains(".")){
            return fileName.substring(0,fileName.lastIndexOf("."));
        }
        else return new File(fileName).getName();
    }

    public static Boolean isNullOrEmpty(String str){
        return str == null || "".equals(str);
    }

    public static void copyStream(InputStream from, OutputStream to) throws Exception{
        byte[] buffer=new byte[2048];
        int length;
        while ((length = from.read(buffer)) > 0) {
            to.write(buffer, 0, length);
        }
    }
    public static void copyFile(String oldPath$Name, String newPath$Name) throws IOException {
        new File(newPath$Name).getParentFile().mkdirs();
        try (FileInputStream fileInputStream = new FileInputStream(oldPath$Name)){
            try (FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name)){
                byte[] buffer = new byte[1024];
                int byteRead;
                while ((byteRead = fileInputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, byteRead);
                }
                fileOutputStream.flush();
            }
        }
    }
    public static boolean isDirectoryExist(String dir){
        File folder = new File(dir);
        return folder.isDirectory();
    }
    public static void createFolder(String dir){
        File folder = new File(dir);
        folder.mkdirs();
    }
    public static void deleteFolder(String dir) throws Exception {
        if(isDirectoryExist(dir)) {
            clearFolder(dir);
            File folder = new File(dir);
            folder.delete();
        }
    }
    public static void clearFolder(String dir) throws Exception {
        File folder = new File(dir);
        if(!folder.isDirectory()) throw new Exception("dir must be folder");
        File[] files=folder.listFiles();
        for(File f :files){
            if(!f.isDirectory()){
                f.delete();
            }
            else{
                clearFolder(f.getPath());
                f.delete();
            }
        }
    }

    public static boolean isFileExist(String file){
        File f = new File(file);
        return f.exists() && f.isFile();
    }

    public static String getFileName(String file){
        return  new File(file).getName();
    }

    public static void saveFile(InputStream inputStream, String path) throws Exception {
        File f = new File(path);
        f.getParentFile().mkdirs();
        try(FileOutputStream outputStream = new FileOutputStream(f)){
            copyStream(inputStream,outputStream);
        };
    }

    public static byte[] readAllBytes(String filename)throws Exception{
        File f = new File(filename);
        if (!f.exists()) {
            throw new FileNotFoundException(filename);
        }
        ArrayList<Byte> buffers=new ArrayList();
        try (FileInputStream in = new FileInputStream(f)){
            try(ByteArrayOutputStream bos=new ByteArrayOutputStream((int)f.length())) {
                int buf_size = 1024;
                byte[] buffer = new byte[buf_size];
                int len = 0;
                while (-1 != (len = in.read(buffer, 0, buf_size))) {
                    bos.write(buffer,0,len);
                }
                return bos.toByteArray();
            }
        }
    }

    public static String byteToHex(int n) {
        String[] hexArray = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
        if (n < 0) {
            n = n + 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexArray[d1] + hexArray[d2];
    }

    public static void writeTxt(String filepath,String txt,String encoding) throws  Exception{
        try(BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filepath),encoding))){
            bw.write(txt);
        }
    }
    public static String readTxt(File txt,String encoding) throws  Exception{
        StringBuilder sb=new StringBuilder();
        try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(txt),encoding))){
            String s = null;
            while((s = br.readLine())!=null){
                if(sb.length()>0){
                    sb.append("\r\n"+s);
                }
                else{
                    sb.append(s);
                }
            }

        }
        return sb.toString();
    }
    public static String readTxt(FileInputStream in,String encoding) throws  Exception{
        StringBuilder sb=new StringBuilder();
        try(BufferedReader br = new BufferedReader(new InputStreamReader(in,encoding))){
            String s = null;
            while((s = br.readLine())!=null){
                if(sb.length()>0){
                    sb.append("\r\n"+s);
                }
                else{
                    sb.append(s);
                }
            }

        }
        return sb.toString();
    }
    public static String readTxt(String filepath,String encoding) throws  Exception{
        return readTxt(new File(filepath),encoding);
    }
    public static long getFileSizeByKb(File f){
        return  getFileSize(f)/1024;
    }
    public static long getFileSizeByMb(File f){
        return  getFileSize(f)/1024/1024;
    }
    public static long getFileSize(File f)
    {
        long size = 0;
        if(f.isFile()){
            size=f.length();
        }
        else {
            File flist[] = f.listFiles();
            for (int i = 0; i < flist.length; i++) {
                if (flist[i].isDirectory()) {
                    size = size + getFileSize(flist[i]);
                } else {
                    size = size + flist[i].length();
                }
            }
        }
        return size;
    }
}
